package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	//允许跨域
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main() {
	http.HandleFunc("/wsmsg", wsmsg)
	http.HandleFunc("/", home)
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}


func wsmsg(w http.ResponseWriter, r *http.Request) {
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
		go writeMsg(c, mt)
	}
}

func writeMsg(conn *websocket.Conn, mt int)  {
	for i := 0; i < 10; i++ {
		time.Sleep(3 * time.Second)
		err := conn.WriteMessage(mt, []byte(fmt.Sprintf("hello_%d", time.Now().Unix())))
		if err != nil {
			log.Println("write error:", err)
			break
		}
	}
}

func home(w http.ResponseWriter, r *http.Request) {
	homeTemplate.Execute(w, "ws://"+r.Host+"/wsmsg")
}

var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>  
window.addEventListener("load", function(evt) {
    
    var ws;
    
    
    
});
</script>
</head>
<body>
</body>
</html>
`))